#include "stdafx.h"
#include "ResponseEntity.h"
#include "Chunk.h"
#include "GZIP.h"
#include "Filter.h"

CResponseEntity::CResponseEntity(CResponseHeader * res, string & strData)
	:m_ResponseHeader(res),
	strData(strData)
{

	m_strEntityBody.append(strData, m_ResponseHeader->getHeaderLength());

	CheckIsGZIP();
}


CResponseEntity::~CResponseEntity()
{
}

void CResponseEntity::ProcessHTML()
{
	//chunked
	if (m_ResponseHeader->getHeader().bChunked) {
		CHTMLParser * pHtmlParse = new CChunk;
		if (pHtmlParse->Process(m_strEntityBody)) {
			m_ResponseHeader->ModifyTransferEncoding_Chunked_none();
			//ReCheck GZIP
			CheckIsGZIP();
		}

		delete pHtmlParse;
		pHtmlParse = nullptr;
	}

	//gzip
	if (m_isGZIP) {
		CHTMLParser * pHtmlParse = new CGZIP;
		if (pHtmlParse->Process(m_strEntityBody)) {
			m_ResponseHeader->ModifyContent_Encoding_GZIP_none();
		}

		delete pHtmlParse;
		pHtmlParse = nullptr;
	}

	//Modify the value of Content-Length:
	m_ResponseHeader->ModifyContentLength(m_strEntityBody.length());

	//filter
	CHTMLParser * pFilter = new CHTMLFilter;
	pFilter->Process(m_strEntityBody);

	delete pFilter;
	pFilter = nullptr;


	//Rebuild data

	strData.assign(m_ResponseHeader->getResponseHeaderString());
	strData.append(m_strEntityBody);
}

void CResponseEntity::CheckIsGZIP()
{
	if (m_strEntityBody.empty())
		m_isGZIP = false;
	else if (m_strEntityBody[0] != 31)
		m_isGZIP = false;
	else if (m_strEntityBody[1] != -117)
		m_isGZIP = false;
	else
		m_isGZIP = true;
}